import * as Blockly from 'blockly/core';
import * as Mixly from 'mixly';

const { MJson } = Mixly;

const generators = {};

const Generator = Blockly.Arduino ?? Blockly.Python;

for (let inputObj of [{
    type: 'ValueInput',
    name: 'block_tool_value_input'
}, {
    type: 'StatementInput',
    name: 'block_tool_statement_input'
}, {
    type: 'DummyInput',
    name: 'block_tool_dummy_input'
}]) {
    generators[inputObj.name] = function () {
        const parent = this.getSurroundParent();
        if (!(parent && parent.type === 'block_tool_main')) {
            return '';
        }
        const NAME = inputObj.type === 'DummyInput' ? '' : this.getFieldValue('NAME');
        if (inputObj.type !== 'DummyInput' && !NAME) {
            return '';
        }
        const VALUE = Generator.statementToCode(this, 'VALUE', Generator.ORDER_ATOMIC).split('\n');
        const ALIGN_TYPE = this.getFieldValue('ALIGN_TYPE');
        // const ALLOW_TYPE = Generator.valueToCode(this, 'ALLOW_TYPE', Generator.ORDER_ATOMIC);
        let blockList = [];
        let generatorList = [];
        for (let elemStr of VALUE) {
            if (!elemStr) {
                continue;
            }
            let elemObj;
            try {
                elemObj = JSON.parse(elemStr)
            } catch (error) {
                elemObj = null;
            }
            if (!elemObj) {
                continue;
            }
            elemObj.block = elemObj.block ?? [];
            elemObj.generator = elemObj.generator ?? [];
            for (let i of elemObj.block) {
                blockList.push('    ' + i);
            }
            for (let i of elemObj.generator) {
                generatorList.push(i);
            }
        }
        let generatorType = '';
        if (Blockly.Arduino) {
            generatorType = 'Blockly.Arduino';
        } else {
            generatorType = 'Blockly.Python';
        }
        switch (inputObj.type) {
        case 'ValueInput':
            generatorList.push(`var VALUE_INPUT_${NAME.toUpperCase()} = ${generatorType}.valueToCode(this, "${NAME}", ${generatorType}.ORDER_ATOMIC);`);
            break;
        case 'StatementInput':
            generatorList.push(`var STATEMENT_INPUT_${NAME.toUpperCase()} = ${generatorType}.statementToCode(this, "${NAME}");`);
            break;
        }
        if (blockList.length) {
            blockList[blockList.length - 1] += ';';
        }
        blockList.unshift(`    .setAlign(${ALIGN_TYPE})${blockList.length ? '' : ';'}`);
        if (inputObj.type !== 'DummyInput') {
            blockList.unshift(`    .setCheck(null)`);
        }
        blockList.unshift(`this.append${inputObj.type}(${NAME ? ('"' + NAME + '"') : ''})`);

        let obj = {
            block: blockList,
            generator: generatorList
        };
        let code = MJson.stringify(obj) + '\n';
        return code;
    };
}

export default generators;